import Vue from "vue";
import Vuex from "vuex";
import { setLang } from "../locales";
import { SET_LANG, SET_ACCOUNT, SET_CONFIG, SET_INDEX_PIC } from "./types";
import { getAccount, getConfig } from "../api/account";
import { getIndexPic } from "../api";
import storage from "@/utils/storage";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    lang: "",
    account: {},
    config: {},
    indexPic: storage.getItem("INDEX_PIC") || {
      bannerList: [],
      brand_com: [],
      coop_com: [],
      coop_com_two: []
    }
  },
  mutations: {
    [SET_LANG](state, lang) {
      state.lang = lang;
    },
    [SET_ACCOUNT](state, account) {
      state.account = account;
    },
    [SET_CONFIG](state, config) {
      state.config = config;
    },
    [SET_INDEX_PIC](state, pic) {
      state.indexPic = pic;
    }
  },
  actions: {
    setLang({ commit }, lang) {
      setLang(lang);
      commit(SET_LANG, lang);
    },
    async getAccountAction({ commit }) {
      const res = await getAccount();
      commit(SET_ACCOUNT, {
        ...res.data
      });
    },
    async getConfig({ commit }) {
      const res = await getConfig();
      commit(SET_CONFIG, res.data);
    },
    async getIndexPic({ commit }) {
      const res = await getIndexPic();
      storage.setItem("INDEX_PIC", res.data);
      commit(SET_INDEX_PIC, res.data);
    }
  },
  getters: {
    lang: state => state.lang,
    account: state => state.account,
    config: state => state.config,
    indexPic: state => state.indexPic
  }
});
